//
//  pakagerForAndroid.m
//  AutoCompiler_Script
//
//  Created by Vescky on 13-4-25.
//  Copyright (c) 2013年 Vescky. All rights reserved.
//

#import "pakagerForAndroid.h"
#import "RegexKitLite.h"
#import "AppsProjectInfoParser.h"
#import "ProjectInfo.h"
#import "DataInfo.h"
//#import "AppDelegate.h"
#import "PathParser.h"
#import "FileOperator.h"
#import "NSImage+Resize.h"

@implementation pakagerForAndroid

@synthesize delegate;

static pakagerForAndroid *pkAndroid;
static NSString *androidProjectId;
AppsImageEngine *imgEngineAndroid;
bool needToBuild;
int androidIconDone;

//NSString *workFolder,*androidHomepagePath,*androidTabsPath,*androidTemplatePath,*androidProjectinfoPath;
bool isLoadingImgComplete;


+ (id)sharePakagerFroAndroid {
    if (!pkAndroid) {
        pkAndroid = [[pakagerForAndroid alloc] init];
//        PathParser *pp = [PathParser sharePathParser];
//        [pkAndroid setPathWithWorkFolderPath:pp.workSpaceFolderPath];
    }
    return pkAndroid;
}

- (void)test {
//  NSArray *xmlList = [self scanForExtention:@"xml" atPath:[NSString stringWithFormat:@"%@/res/layout",Android_Template_Path]];
    
//    if ([self initAndroidProject]) {
//        [self parseForInfo];
//        [self modifyMenifestWithAppName:@"carKeeper" appId:@"402882e53dcf0748013ddd64f28713fa"];
//    }
//    else {
//        NSLog(@"initial fialed!");
//    }
//
//    [self modifyProject];
//    [(AppDelegate*)[[NSApplication sharedApplication] delegate] workSpaceForAutoCompiler];

}


//- (void)autoRunWithAppBundleID:(NSString*)appBundleID {
//    ProjectInfo *pInfo = [AppsProjectInfoParser parseProjectInfo];
//    imgEngineAndroid = [AppsImageEngine sharedEngine];
//    imgEngineAndroid.delegate = self;
//    needToBuild = NO;
//    
//    if ([self initAndroidProject]) {
//        
//        [self parseForInfo];
//        [self modifyMenifestWithAppName:appBundleID appId:pInfo.projectID];
//        [self modifyProject:@"wip"];
//        [self modifyAntProperticesWithAppName:pInfo.appsName];
//        
//        //load完图片后调用build命令
//        int i = 0;
//        while (1) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//            [NSThread sleepForTimeInterval:1.0];
//            if (isLoadingImgComplete || i >= 90) {
//                NSLog(@"i = %d,loading = %d\n",i,isLoadingImgComplete);
//                isLoadingImgComplete = NO;
//                [self androidBuildWithLogFiles:NO];
//                break;
//            }
//            i++;
//        }
//    
//    }
//    else {
//        NSLog(@"########## initial fialed! #########\n");
//    }
//}


//- (void)autoCompileAndroid:(NSString*)enName environment:(NSString*)environment createLogFile:(bool)isLogfile {
//    ProjectInfo *pInfo = [AppsProjectInfoParser parseProjectInfo];
//    imgEngineAndroid = [AppsImageEngine sharedEngine];
//    imgEngineAndroid.delegate = self;
//    needToBuild = NO;
//    
//    if ([self initAndroidProject]) {
//        
//        [self parseForInfo];
//        [self modifyMenifestWithAppName:enName appId:pInfo.projectID];
//        [self modifyProject:environment];
//        [self ModifyServerIP:environment];
//        [self modifyAntProperticesWithAppName:enName];
//        
//        //load完图片后调用build命令
//        int i = 0;
//        while (i < 100) {
////            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//            [NSThread sleepForTimeInterval:1.0];
//            printf("waiting for image download:%ds\n",i);
//            if (androidIconDone > 3 || i >= 90) {
//                NSLog(@"total:%ds,loading = %d\n",i,androidIconDone);
//                androidIconDone = 0;
////                [self androidBuildWithLogFiles:isLogfile];
//                break;
//            }
//            i++;
//        }
//        
//    }
//    else {
//        NSLog(@"######### initial fialed! ############\n");
//    }
//    
//}



//通过dictionary穿参数  -------  目前为止的最新调用方法 2013.10 --------
- (void)autoCompileAndroidWithContent:(NSMutableDictionary*)content {
    ProjectInfo *pInfo = [AppsProjectInfoParser parseProjectInfo];
    imgEngineAndroid = [AppsImageEngine sharedEngine];
    imgEngineAndroid.delegate = self;
    
    NSString *enName = [content objectForKey:@"enname"];
    NSString *environment = [content objectForKey:@"environment"];//一个ip地址
    NSString *buildFlag = [content objectForKey:@"build"];
    NSString *isLogfile = [content objectForKey:@"save"];
    NSString *xmppIp = [content objectForKey:@"xmppIp"];
    NSString *mode = [content objectForKey:@"mode"];//0普通app，1商圈Publish，2商圈Preview
    
    if ([self initAndroidProject]) {
        
        [self parseForInfoWithMode:[mode intValue]];
        [self modifyMenifestWithAppName:enName appId:pInfo.projectID];
        [self modifyProject:environment withMode:mode];
        [self ModifyServerIP:environment];
        [self ModifyXmppIP:xmppIp];
        [self modifyAntProperticesWithAppName:enName];
        
        //load完图片后调用build命令
        int i = 0;
        while (i < 100) {
            [NSThread sleepForTimeInterval:1.0];
            printf("waiting for image download:%ds\n",i);
            if (androidIconDone > 3 || i >= 90) {
                NSLog(@"total:%ds,loading = %d\n",i,androidIconDone);
                if (buildFlag && [buildFlag isEqualToString:@"YES"]) {
                    bool flag = NO;
                    if (isLogfile && [isLogfile isEqualToString:@"YES"]) {
                        flag = YES;
                    }
                    [self androidBuildWithLogFiles:flag];
                }
                androidIconDone = 0;
                break;
            }
            i++;
        }
        
    }
    else {
        NSLog(@"######### initial fialed! ############\n");
    }

}

#pragma mark - 步骤1 初始化
- (bool)initAndroidProject {
    
    NSLog(@">>>>>>>>>>>>>>>>>>>Android: Initializing work space,it takes about 1 min... <<<<<<<<<<<<<<<<<<<<<<<<\n");
    
    NSFileManager *fm = [[NSFileManager alloc] init];

    PathParser *pp = [PathParser sharePathParser];

    NSString *tPath = pp.defaultAndroidProjectPath;
    
    NSString *mPath = pp.outAndroidProjectPath;//[NSString stringWithFormat:@"%@/Android/AppsTemplate",WORK_FOLDER];
    if (![fm fileExistsAtPath:tPath]) {
        printf("%s\n",[tPath UTF8String]);
        return NO;
    }
    
    if ([fm fileExistsAtPath:mPath] ) {
        [fm removeItemAtPath:mPath error:nil];
    }
    
    NSLog(@"copying %s to %s .........\n",[tPath UTF8String],[mPath UTF8String]);
    
    [fm copyItemAtPath:tPath toPath:mPath error:nil];
    
    return YES;
    
}

#pragma mark - 步骤2 获取四种程序图标、更改应用程序名称、复制bundle到android目录中
- (void)modifyProject:(NSString*)environment withMode:(NSString*)_mode {
    NSLog(@">>>>>>>>>>>>>>>>>>>Android: Modifying app info,it takes about 10s... <<<<<<<<<<<<<<<<<<<<<<<<\n");
    
    PathParser *pp = [PathParser sharePathParser];
    
    ProjectInfo *pInfo = [AppsProjectInfoParser parseProjectInfo];
    //---------下载程序图标
    environment = [environment lowercaseString];
    if ([environment isEqualToString:@"no"]) {
        isLoadingImgComplete = YES;
    }
    else {
        isLoadingImgComplete = NO;
//        [imgEngineAndroid loadAndroidIconWithImageUrl:pInfo.icon projectPath:pp.outAndroidProjectPath];
        
        //zip包没有才从服务器下载
        FileOperator *fop = [FileOperator shareFileOperator];
        NSString *bigIconPath = [fop getIconPathFromZip];
        if (bigIconPath) {
            NSImage *bigIcon = [NSImage imageNamed:bigIconPath];
            if (bigIcon) {
                //32,48,72,96
                [self saveIconWithLocalIconImage:bigIcon];
                isLoadingImgComplete = YES;
            }
            else {
                [self loadAndroidIconsUsingGCDWithImageUrl:pInfo.icon projectPath:pp.outAndroidProjectPath];
            }
        }
        else {
            [self loadAndroidIconsUsingGCDWithImageUrl:pInfo.icon projectPath:pp.outAndroidProjectPath];
        }
    }
    
    //---------更改程序名称和version
    NSString *vName = pInfo.version;
    vName = [vName lowercaseString];
    vName = [vName stringByReplacingOccurrencesOfString:@"v" withString:@""];
    
#pragma mark - 修改 strings.sml
    NSString *sPath = [NSString stringWithFormat:@"%@/res/values/strings.xml",pp.outAndroidProjectPath];//strings.xml文件的位置
    NSString *str = [[NSString alloc] initWithContentsOfFile:sPath encoding:NSUTF8StringEncoding error:nil];
    str = [str stringByReplacingOccurrencesOfString:@"XAPPS123X_APPNAME" withString:pInfo.appsName];
    [str writeToFile:sPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSString *sEnPath = [NSString stringWithFormat:@"%@/res/values-en/strings.xml",pp.outAndroidProjectPath];//en-strings.xml文件的位置
    NSString *enStr = [[NSString alloc] initWithContentsOfFile:sEnPath encoding:NSUTF8StringEncoding error:nil];
    enStr = [enStr stringByReplacingOccurrencesOfString:@"XAPPS123X_APPNAME" withString:pInfo.appsName];
    [enStr writeToFile:sEnPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSString *mPath = [NSString stringWithFormat:@"%@/AndroidManifest.xml",pp.outAndroidProjectPath];//AndroidManifest.xml文件的位置
    NSString *str1 = [[NSString alloc] initWithContentsOfFile:mPath encoding:NSUTF8StringEncoding error:nil];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_VERSIONCODE" withString:[NSString stringWithFormat:@"%d",[vName intValue]]];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_VERSIONNAME" withString:[NSString stringWithFormat:@"%.1f",[vName floatValue]]];
    [str1 writeToFile:mPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //---------复制bundle过去
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSString *goalPath = [NSString stringWithFormat:@"%@/assets/%@",pp.outAndroidProjectPath,pp.incomeBundleName];
    if ([fm fileExistsAtPath:goalPath]) {
        [fm removeItemAtPath:goalPath error:nil];
    }
    [fm copyItemAtPath:pp.incomeBundlePath toPath:goalPath error:nil];
    //去掉.bundle的后缀
    NSString *goalDir = [goalPath stringByDeletingPathExtension];//[goalPath stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",[goalPath pathExtension]] withString:@""];
    if ([fm fileExistsAtPath:goalDir]) {
        [fm removeItemAtPath:goalDir error:nil];
    }
    [fm moveItemAtPath:goalPath toPath:goalDir error:nil];
    
    
#pragma mark - 修改测试警告信息
    NSString *constantsPath = [NSString stringWithFormat:@"%@/src/cn/apps123/base/constants/AppsConstants.java",pp.outAndroidProjectPath];
    NSString *conContent = [NSString stringWithContentsOfFile:constantsPath encoding:NSUTF8StringEncoding error:nil];
    
    int bMode = [_mode integerValue] % 100;
    
    //判断是否为商圈的app
    if (bMode % 3 == 1) {//bMode == 1 || bMode == 4
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"false"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"false"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"prod"];
    }
    else if (bMode % 3 == 2) {//bMode == 2 || bMode == 5
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"true"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"true"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"wip"];
    }
    else {
        if ([environment isEqualToString:pp.wipServerIP]) {
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"true"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"true"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"wip"];
        }
        else {
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"false"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"false"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"prod"];
        }
    }
    //修改googlemap配置
    DataInfo *dInfo = [AppsProjectInfoParser parseDataInfo];
    if (dInfo.mapType == GoogleMap) {
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_GOOGLEMAP" withString:@"true"];
    }
    
    [conContent writeToFile:constantsPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

#pragma mark - 步骤3 解析zip包信息
- (void)parseForInfoWithMode:(int)mode {
    NSLog(@">>>>>>>>>>>>>>>>>>>Android: Parsing zip package,i takes about 30s... <<<<<<<<<<<<<<<<<<<<<<<<\n");
    
    NSMutableArray *viewName = [[NSMutableArray alloc] init];
    NSMutableArray *viewLayout = [[NSMutableArray alloc] init];
    DataInfo *dInfo = [AppsProjectInfoParser parseDataInfo];
//    NSLog(@"1");
    HomePageDataListItem *hpItem = [dInfo.dataList objectAtIndex:1];
    if (hpItem.sysTabName) {
        [viewName addObject:hpItem.sysTabName];
    }
    if (hpItem.layout) {
        [viewLayout addObject:hpItem.layout];
    }
    
    //More Layout
    [viewName addObject:@"more"];
    if (dInfo.moreLayout) {
        [viewLayout addObject:dInfo.moreLayout];
    }
    
//    NSLog(@"2");
    for (int i = 2; i < [dInfo.dataList count]; i++) {
        TabDataListItem *item = [dInfo.dataList objectAtIndex:i];
        if (item.sysTabName) {
           [viewName addObject:item.sysTabName]; 
        }
        if (item.layout) {
            [viewLayout addObject:item.layout];
        }
    }
//    NSLog(@"3");
    if (mode == 0) {
        
        [self delDocumentWithTabList:viewName layoutList:viewLayout];
    }
    else {
        NSLog(@"\n\n------ not normal template,do not delete any file!  ------\n\n\n");
    }
    
//    NSMutableDictionary *pTabsList = [self toTabLayoutDictionaryWithTabsList:viewName layoutList:viewLayout];
}

#pragma mark - 步骤4 删除多余的包和layout布局文件(xml)
//先homepage，后tabs。tabs中，先删除tab，再删除layout
- (void)delDocumentWithTabList:(NSMutableArray*)tabList layoutList:(NSMutableArray*)layoutList {
    NSLog(@">>>>>>>>>>>>>>>>>>>>>>Android: Picking files,it takes about 1~2 min... <<<<<<<<<<<<<<<<<<<<<<<<<<\n");
    
    if ([layoutList count] < 2) {
        NSLog(@"###################### ERROR:解析zip包出错 ######################");
        return;
    }
    
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSMutableDictionary *pTabsListDict = [self toTabLayoutDictionaryWithTabsList:tabList layoutList:layoutList];
    
    NSString *homePageLayout = [layoutList objectAtIndex:0];
    NSString *moreLayout = [layoutList objectAtIndex:1];
    
    PathParser *pp = [PathParser sharePathParser];
    NSString *androidHomepagePath = [NSString stringWithFormat:@"%@/src/cn/apps123/shell/home_page",pp.outAndroidProjectPath];
    NSString *androidTabsPath = [NSString stringWithFormat:@"%@/src/cn/apps123/shell/tabs",pp.outAndroidProjectPath];
    NSString *androidMorePagePath = [NSString stringWithFormat:@"%@/src/cn/apps123/shell/more",pp.outAndroidProjectPath];
    
#pragma mark ---------- 删除目录中的java文件，即删除layout ----------
    
    //------------  删除homepage的多余layout  ------------
    NSMutableArray *hpLayoutList = [self getListOfPath:androidHomepagePath isDir:YES];
    for (int i = 0; i < [hpLayoutList count]; i++) {
        NSString *hplName = [hpLayoutList objectAtIndex:i];
        if ([hplName isEqualToString:homePageLayout] || [hplName isEqualToString:@"base"] || [hplName isEqualToString:@".svn"]) {
//            [hpLayoutList insertObject:@"" atIndex:i];
            continue;
        }
        else {
            //删除无用的layout
            NSLog(@">>>>>>>>>>>> delete %s\n",[[androidHomepagePath stringByAppendingPathComponent:hplName] UTF8String]);
            [fm removeItemAtPath:[androidHomepagePath stringByAppendingPathComponent:hplName] error:nil];
        }
    }
    
    //------------  删除More的多余layout  ------------
    NSMutableArray *moreLayoutList = [self getListOfPath:androidMorePagePath isDir:YES];
    for (int i = 0; i < [moreLayoutList count]; i++) {
        NSString *morelName = [moreLayoutList objectAtIndex:i];
        if ([morelName isEqualToString:moreLayout] || [morelName isEqualToString:@"base"] || [morelName isEqualToString:@".svn"]) {
            continue;
        }
        else {
            //删除无用的layout
            NSLog(@">>>>>>>>>>>> delete %s\n",[[androidMorePagePath stringByAppendingPathComponent:morelName] UTF8String]);
            [fm removeItemAtPath:[androidMorePagePath stringByAppendingPathComponent:morelName] error:nil];
        }
    }
  
    //------------  先删除tab ------------
    NSMutableArray *tTabsList = [[NSMutableArray alloc] init];
    tTabsList = [self getListOfPath:androidTabsPath isDir:YES];
    
    //删除多余的tab
    for (int i = 0; i < [tTabsList count]; i++) {
        NSString *tabName = [tTabsList objectAtIndex:i];
        if (![pTabsListDict objectForKey:tabName] && ![tabName isEqualToString:@".svn"]) {
            NSLog(@">>>>>>>>>>>> delete %s\n",[[androidTabsPath stringByAppendingPathComponent:tabName] UTF8String]);
            [fm removeItemAtPath:[androidTabsPath stringByAppendingPathComponent:tabName] error:nil];
        }
    }
    
    NSEnumerator *tabsEm = [pTabsListDict keyEnumerator];
    for (NSString *tabName in tabsEm) {
        if (!tabName || tabName.length <= 0) {
            continue;
        }
        NSMutableArray *tabLayoutList = [self getListOfPath:[androidTabsPath stringByAppendingPathComponent:tabName] isDir:YES];
        for (int i = 0; i < [tabLayoutList count]; i++) {
            NSString *layoutName = [tabLayoutList objectAtIndex:i];
            if (!layoutName || layoutName.length <= 0) {
                continue;
            }
            NSMutableArray *arr = [pTabsListDict objectForKey:tabName];
            bool isExist = NO;
            for (int j = 0; j < [arr count]; j++) {
                if ([layoutName isEqualToString:[arr objectAtIndex:j]] || [layoutName isEqualToString:@"base"] || [layoutName isEqualToString:@".svn"]) {
                    isExist = YES;
                    break;
                }
            }
            if (!isExist) {
                NSLog(@">>>>>>>>>>>> delete %s\n",[[NSString stringWithFormat:@"%@/%@/%@",androidTabsPath,tabName,layoutName] UTF8String]);
                [fm removeItemAtPath:[NSString stringWithFormat:@"%@/%@/%@",androidTabsPath,tabName,layoutName] error:nil];
            }
        }
    }

//#ifdef DEL_XML
#pragma mark ---------- 删除xml文件  ----------
    //------------ 删除xml文件  ----------------
    NSArray *xmlList = [self scanForExtention:@"xml" atPath:[NSString stringWithFormat:@"%@/res/layout",pp.outAndroidProjectPath]];
    for (int i = 0; i < [xmlList count]; i++) {
        NSString *xmlName = [xmlList objectAtIndex:i];
        if ([xmlName stringByMatching:@"^base_.*?$"] || [xmlName stringByMatching:@"^activity_base_.*?$"] || [xmlName stringByMatching:@"^adapter_base_.*?$"] || [xmlName stringByMatching:@"^fragement_base_.*?$"]) {
            //公共基础类，全部保留
            continue;
        }
        //fragment开头
        else if([xmlName stringByMatching:@"^fragment_tabs_.*?$"]) {
            
            if ([xmlName stringByMatching:@"^fragment_tabs_.*?_base[_|.].*?$"]) {
                NSString *tnStr = [xmlName stringByMatching:@"tabs_.*?_base"];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"tabs_" withString:@""];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"_base" withString:@""];
                if (![pTabsListDict objectForKey:tnStr]) {
                    //不存在，删除
                    NSLog(@"########### delete %@,tabName:%@ ###########",xmlName,tnStr);
                    [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
                }
            }
            else {
                NSString *tnStr = [xmlName stringByMatching:@"tabs_.*?_layout"];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"tabs_" withString:@""];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"_layout" withString:@""];
                
                NSString *layoutStr = [xmlName stringByMatching:@"layout.*?[_|.]"];
                layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"_" withString:@""];
                layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"." withString:@""];
                layoutStr = [layoutStr lowercaseString];
                
                NSMutableArray *arr = [pTabsListDict objectForKey:tnStr];
                bool isReserved = NO;
                for (int j = 0; j < [arr count]; j++) {
                    if ([[arr objectAtIndex:j] isEqualToString:layoutStr]) {
                        isReserved = YES;
                        break;
                    }
                }
                if (!isReserved) {
                    //删除
                    NSLog(@"########### delete %@ ,tabName:%@,layoutName:%@###########",xmlName,tnStr,layoutStr);
                    [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
                }
            }
            
        }
        //homepage类
        else if([xmlName stringByMatching:@"^activity_home_page_.*?$"] || [xmlName stringByMatching:@"^adapter_home_page_.*?$"] || [xmlName stringByMatching:@"^fragment_home_page_.*?$"]) {
//            NSMutableArray *arr = [pTabsListDict objectForKey:@"home_page"];
            if ([xmlName stringByMatching:homePageLayout] || [xmlName stringByMatching:@"_base_"]) {
                continue;
            }
            else {
                //删除
                NSLog(@"########### delete %@ ###########",xmlName);
                [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
            }
        }
        //More类
        else if([xmlName stringByMatching:@"^activity_more_.*?$"] || [xmlName stringByMatching:@"^adapter_more_.*?$"] || [xmlName stringByMatching:@"^fragment_more_.*?$"]) {
            //            NSMutableArray *arr = [pTabsListDict objectForKey:@"home_page"];
            if ([xmlName stringByMatching:moreLayout] || [xmlName stringByMatching:@"_base_"]) {
                continue;
            }
            else {
                //删除
                 NSLog(@"########### delete %@ ###########",xmlName);
                [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
            }
        }
        //adapter开头
        else if([xmlName stringByMatching:@"^adapter_tabs_.*?$"]) {
            if ([xmlName stringByMatching:@"^adapter_tabs_.*?_base[_|.].*?$"]) {
                NSString *tnStr = [xmlName stringByMatching:@"tabs_.*?_base"];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"tabs_" withString:@""];
                tnStr = [tnStr stringByReplacingOccurrencesOfString:@"_base" withString:@""];
                if (![pTabsListDict objectForKey:tnStr]) {
                    //不存在，删除
                    NSLog(@"########### delete %@,tabName:%@ ###########",xmlName,tnStr);
                    [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
                }
            }
            else {
                NSString *tnStr = [xmlName stringByReplacingOccurrencesOfRegex:@"^.*?_tabs_" withString:@""];
                tnStr = [tnStr stringByReplacingOccurrencesOfRegex:@"_layout.*?$" withString:@""];
                
                NSString *layoutStr = [xmlName stringByMatching:@"layout.*?[_|.]"];
                layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"_" withString:@""];
                layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"." withString:@""];
                layoutStr = [layoutStr lowercaseString];
                
                NSMutableArray *arr = [pTabsListDict objectForKey:tnStr];
                bool isReserved = NO;
                for (int j = 0; j < [arr count]; j++) {
                    if ([[arr objectAtIndex:j] isEqualToString:layoutStr]) {
                        isReserved = YES;
                        break;
                    }
                }
                if (!isReserved) {
                    //删除
                    NSLog(@"########### delete %@ ,tabName:%@,layoutName:%@###########",xmlName,tnStr,layoutStr);
                    [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
                }
            }
        }
        //activity开头
        else if([xmlName stringByMatching:@"^activity_tabs_.*?$"]) {
            NSString *tnStr = [xmlName stringByReplacingOccurrencesOfRegex:@"^.*?_tabs_" withString:@""];
            tnStr = [tnStr stringByReplacingOccurrencesOfRegex:@"_layout.*?$" withString:@""];
            
            NSString *layoutStr = [xmlName stringByMatching:@"layout.*?[_|.]"];
            layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"_" withString:@""];
            layoutStr = [layoutStr stringByReplacingOccurrencesOfString:@"." withString:@""];
            layoutStr = [layoutStr lowercaseString];
            
            NSMutableArray *arr = [pTabsListDict objectForKey:tnStr];
            bool isReserved = NO;
            for (int j = 0; j < [arr count]; j++) {
                if ([[arr objectAtIndex:j] isEqualToString:layoutStr]) {
                    isReserved = YES;
                    break;
                }
            }
            if (!isReserved) {
                //删除
                NSLog(@"########### delete %@ ,tabName:%@,layoutName:%@###########",xmlName,tnStr,layoutStr);
                [fm removeItemAtPath:[NSString stringWithFormat:@"%@/res/layout/%@",pp.outAndroidProjectPath,xmlName] error:nil];
            }
        }
//        else if([xmlName stringByMatching:@"^adapter_tabs_.*?$"]) {
//            
//        }

        
    }

}

//遍历当前目录，返回一个列表
- (NSMutableArray*)getListOfPath:(NSString*)gPath isDir:(bool)dir {
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSArray *fileList = [[NSArray alloc] init];
    fileList = [fm contentsOfDirectoryAtPath:gPath error:nil];
    NSMutableArray *fileArray = [[NSMutableArray alloc] init];
    NSMutableArray *folderArray = [[NSMutableArray alloc] init];
    BOOL isDir = NO;
    for (NSString *file in fileList) {
        NSString *path = [gPath stringByAppendingPathComponent:file];
        [fm fileExistsAtPath:path isDirectory:(&isDir)];
        if (!isDir) {
            [fileArray addObject:file];
        }
        else {
            [folderArray addObject:file];
        }
        isDir = NO;
    }
    
    if (dir) {
        return folderArray;
    }
    else {
        return fileArray;
    }
}

- (NSMutableDictionary*)toTabLayoutDictionaryWithTabsList:(NSMutableArray*)tabList layoutList:(NSMutableArray*)layoutList {
    NSMutableDictionary *rDict = [[NSMutableDictionary alloc] init];
    //0是homgpage
    for (int i = 1; i < [tabList count]; i++) {
        NSString *tabName = [tabList objectAtIndex:i];
        tabName = [tabName stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
        tabName = [tabName lowercaseString];
        if ([rDict objectForKey:tabName]) {
            NSMutableArray *arr = [rDict objectForKey:tabName];
            [arr addObject:[layoutList objectAtIndex:i]];
        }
        else {
            NSMutableArray *arr = [[NSMutableArray alloc] init];
            [arr addObject:[layoutList objectAtIndex:i]];
            [rDict setObject:arr forKey:tabName];
        }
    }
    return rDict;
}

//扫描目录中，所有特定后缀的文件列表
- (NSMutableArray*)scanForExtention:(NSString*)pExtention atPath:(NSString*)path {
    pExtention = [pExtention lowercaseString];//转换成小写，方便比较
    
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSArray *mList = [fm contentsOfDirectoryAtPath:path error:nil];
    NSMutableArray *rArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < [mList count]; i++) {
        NSString *fName = [mList objectAtIndex:i];
        if ([[[fName pathExtension] lowercaseString] isEqualToString:pExtention]) {
            [rArray addObject:fName];
        }
    }
    return rArray;
}

#pragma mark - 步骤5 修改配置文件
//修改manifest
- (void)modifyMenifestWithAppName:(NSString*)appName appId:(NSString*)appId {//AndroidManifest.xml
    
    NSLog(@">>>>>>>>>>>>>>>>>>>Android: Modifying config files,it takes about 20s... <<<<<<<<<<<<<<<<<<<<<<<\n");
    PathParser *pp = [PathParser sharePathParser];
    
    androidProjectId = appId;
    
    NSFileManager *fm = [[NSFileManager alloc] init];
    
    //修改menifest的内容
    NSString *str = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/AndroidManifest.xml",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@",str);
//    str = [str stringByReplacingOccurrencesOfString:@"package=\"cn.apps123.shell.hs\"" withString:[NSString stringWithFormat:@"package=\"cn.apps123.shell.%@\"",appName]];
//    str = [str stringByReplacingOccurrencesOfRegex:@"cn_apps123_PushNotificationStart_.*?\"" withString:[NSString stringWithFormat:@"cn_apps123_PushNotificationStart_%@",appId]];
    str = [str stringByReplacingOccurrencesOfString:@"XAPPS123X_PACKAGENAME" withString:appName];
    str = [str stringByReplacingOccurrencesOfString:@"XAPPS123X_APPID" withString:appId];
    [str writeToFile:[NSString stringWithFormat:@"%@/AndroidManifest.xml",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //修改目录中的主包名
    NSString *bPath = [NSString stringWithFormat:@"%@/src/cn/apps123/shell/XAPPS123X_PACKAGENAME",pp.outAndroidProjectPath];
    NSString *gPath = [NSString stringWithFormat:@"%@/src/cn/apps123/shell/%@",pp.outAndroidProjectPath,appName];
    [fm moveItemAtPath:bPath toPath:gPath error:nil];
    
    //修改主包目录中的package
    NSArray *mList = [fm contentsOfDirectoryAtPath:gPath error:nil];
    for (int i = 0; i < [mList count]; i++) {
        NSString *fName = [mList objectAtIndex:i];
        if ([[[fName pathExtension] lowercaseString] isEqualToString:@"java"]) {
            NSString *str = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",gPath,fName] encoding:NSUTF8StringEncoding error:nil];
//            str = [str stringByReplacingOccurrencesOfString:@"package cn.apps123.shell.hs;" withString:[NSString stringWithFormat:@"package cn.apps123.shell.%@;",appName]];
            str = [str stringByReplacingOccurrencesOfString:@"XAPPS123X_PACKAGENAME" withString:appName];
            [str writeToFile:[NSString stringWithFormat:@"%@/%@",gPath,fName] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
    }
    
    //修改所有引用了主包的文件
    [self modifyAllFilesInPath:[NSString stringWithFormat:@"%@/src",pp.outAndroidProjectPath] newName:appName oldName:@"XAPPS123X_PACKAGENAME"];
    
    //修改main.properties的内容
    NSString *str1 = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_PACKAGENAME" withString:appName];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_APPID" withString:appId];
    [str1 writeToFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
}


//修改所有引用了主包的文件
- (void)modifyAllFilesInPath:(NSString*)path newName:(NSString*)newName oldName:(NSString*)oldName {
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSArray *fileList = [[NSArray alloc] init];
    fileList = [fm contentsOfDirectoryAtPath:path error:nil];
    for (int i = 0; i < [fileList count]; i++) {
        NSString *fName = [fileList objectAtIndex:i];
        if ([fName isEqualToString:@".svn"] || [fName isEqualToString:@".DS_Store"]) {
            continue;
        }
        else if([[[fName pathExtension] lowercaseString] isEqualToString:@"java"]) {
            //修改
            NSLog(@">>>>>>>>>>>> modify:%s\n",[fName UTF8String]);
            NSString *str = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",path,fName] encoding:NSUTF8StringEncoding error:nil];
            str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"import cn.apps123.shell.%@",oldName] withString:[NSString stringWithFormat:@"import cn.apps123.shell.%@",newName]];
            [str writeToFile:[NSString stringWithFormat:@"%@/%@",path,fName] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        BOOL isDir = NO;
        [fm fileExistsAtPath:[path stringByAppendingPathComponent:fName] isDirectory:&isDir];
        if (isDir) {
            [self modifyAllFilesInPath:[path stringByAppendingPathComponent:fName] newName:newName oldName:oldName];
        }
    }
}

//修改IP地址
- (bool)ModifyServerIP:(NSString*)ipAddress {
    if (!ipAddress || ipAddress.length <= 0) {
        return NO;
    }
    PathParser *pp = [PathParser sharePathParser];
    NSString *fPath = [NSString stringWithFormat:@"%@/res/values/strings.xml",pp.outAndroidProjectPath];
    NSString *cnString = [[NSString alloc] initWithContentsOfFile:fPath encoding:NSUTF8StringEncoding error:nil];
    cnString = [cnString stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERIP" withString:ipAddress];
    [cnString writeToFile:fPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSString *fEnPath = [NSString stringWithFormat:@"%@/res/values-en/strings.xml",pp.outAndroidProjectPath];
    NSString *enString = [[NSString alloc] initWithContentsOfFile:fEnPath encoding:NSUTF8StringEncoding error:nil];
    enString = [enString stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERIP" withString:ipAddress];
    [enString writeToFile:fEnPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSString *str1 = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERIP" withString:ipAddress];
    [str1 writeToFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

- (bool)ModifyXmppIP:(NSString*)ipAddress {
    if (!ipAddress || ipAddress.length <= 0) {
        return NO;
    }
    PathParser *pp = [PathParser sharePathParser];
    NSString *str1 = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERXMPPIP" withString:ipAddress];
    [str1 writeToFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
//    NSString *str2 = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
//    str2 = [str2 stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERXMPPIP" withString:ipAddress];
//    [str2 writeToFile:[NSString stringWithFormat:@"%@/res/raw/main.properties",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

- (bool)modifyAntProperticesWithAppName:(NSString*)appName {
    if (!appName || appName.length < 1) {
        return NO;
    }
    
    //修改ant配置文件
    PathParser *pp = [PathParser sharePathParser];
    
    //-----更改ant.properties中的apk名称和apk路径
    NSString *antPt = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/ant.properties",pp.outAndroidProjectPath] encoding:NSUTF8StringEncoding error:nil];
    if (!antPt || antPt.length < 1) {
        NSLog(@"################## ERROR:ant.propertices can be null! ########################\n");
        return NO;
    }
    
    antPt = [antPt stringByReplacingOccurrencesOfRegex:@"out.customize.dir=.*?\n" withString:[NSString stringWithFormat:@"out.customize.dir=%@\n",pp.outputAppPath]];
    antPt = [antPt stringByReplacingOccurrencesOfRegex:@"out.customize.package.name=.*?\n" withString:[NSString stringWithFormat:@"out.customize.package.name=%@\n",appName]];
    [antPt writeToFile:[NSString stringWithFormat:@"%@/ant.properties",pp.outAndroidProjectPath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    return YES;
}


#pragma mark - 步骤6 调用ant命令编译工程
- (void)androidBuildWithLogFiles:(bool)isLogsFile {
    NSLog(@">>>>>>>>>>>>>>>>>>>Android: Compiling project,it takes about 2 mins... <<<<<<<<<<<<<<<\n");
    
    PathParser *pp = [PathParser sharePathParser];
    NSString *scriptPath = pp.scriptFilesPath;
    NSString *outPath = pp.outAndroidProjectPath;
    
    //去空格
    scriptPath = [scriptPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    outPath = [outPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    
    NSString *buildCommand = [NSString stringWithFormat:@"%@/AntBuild.sh 0 %@",pp.scriptFilesPath,pp.outAndroidProjectPath];//1-debug,0-release
    
    if (isLogsFile) {
       NSString *buildLogPath = [pp.outputLogFilesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Android_CompileLog.log"]];
        mysystem1([buildCommand UTF8String], (char*)[buildLogPath UTF8String]);
    }
    else {
        system([buildCommand UTF8String]);
    }
    
    printf("Android: Compile done\n");
    
    //回调函数
    if ([delegate respondsToSelector:@selector(androidAutoRunDone)]) {
        [delegate androidAutoRunDone];
    }
}

int mysystem1(const char* cmdstring,char* tmpfile)
{
    char cmd_string[1024];
    
    //    tmpnam(tmpfile);
    FILE *file = fopen(tmpfile, "a+");
    if (!file) {
        return -1;
    }
    fclose(file);
    
    sprintf(cmd_string, "%s > %s", cmdstring, tmpfile);
    
    return system(cmd_string);
}


#pragma mark - AppsImageEngineDelegate
- (void)AppsImageEngineLoadAndroidIconsComplete {
    NSLog(@"Android: load android icons done!\n");
//    [NSThread sleepForTimeInterval:5.0];
    isLoadingImgComplete = YES;
//    [self androidBuild];
}

- (void)loadAndroidIconsUsingGCDWithImageUrl:(NSString*)url projectPath:(NSString*)pPath {
    androidIconDone = 0;
    NSString *ext = [url pathExtension];
    url = [url stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",ext] withString:@""];//去掉尾部
    __block NSString *iconH = [NSString stringWithFormat:@"%@_r72x72.%@",url,ext];
    __block NSString *iconL = [NSString stringWithFormat:@"%@_r32x32.%@",url,ext];
    __block NSString *iconM = [NSString stringWithFormat:@"%@_r48x48.%@",url,ext];
    __block NSString *iconXH = [NSString stringWithFormat:@"%@_r96x96.%@",url,ext];
    
    dispatch_queue_t queue1 = dispatch_queue_create("DownloadIcons", NULL);
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconH]];
        result = [[NSImage alloc] initWithData:data];
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-hdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for hdpi complete! No.%d\n",androidIconDone);
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconL]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-ldpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for ldpi complete! No.%d\n",androidIconDone);
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconM]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-mdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for mdpi complete! No.%d\n",androidIconDone);
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconXH]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-xhdpi/icon.png"]];
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for xhdpi complete! No.%d\n",androidIconDone);
    });
}

- (bool)saveIconWithLocalIconImage:(NSImage*)bigImage {
    
    if (!bigImage) {
        return NO;
    }
    
    NSImage *hIconImage = [bigImage scaleToSize:CGSizeMake(72.0, 72.0)];
    NSImage *mIconImage = [bigImage scaleToSize:CGSizeMake(48.0, 48.0)];
    NSImage *lIconImage = [bigImage scaleToSize:CGSizeMake(32.0, 32.0)];
    NSImage *xhIconImage = [bigImage scaleToSize:CGSizeMake(96.0, 96.0)];
    
    PathParser *pp = [PathParser sharePathParser];
    NSString *hIconPath = [pp.outAndroidProjectPath stringByAppendingPathComponent:@"res/drawable-hdpi/icon.png"];
    NSString *lIconPath = [pp.outAndroidProjectPath stringByAppendingPathComponent:@"res/drawable-ldpi/icon.png"];
    NSString *mIconPath = [pp.outAndroidProjectPath stringByAppendingPathComponent:@"res/drawable-mdpi/icon.png"];
    NSString *xhIconPath = [pp.outAndroidProjectPath stringByAppendingPathComponent:@"res/drawable-xhdpi/icon.png"];
    
    [[AppsImageEngine sharedEngine] saveImage:lIconImage saveType:NSPNGFileType properties:nil ToTarget:lIconPath];
    [[AppsImageEngine sharedEngine] saveImage:mIconImage saveType:NSPNGFileType properties:nil ToTarget:mIconPath];
    [[AppsImageEngine sharedEngine] saveImage:hIconImage saveType:NSPNGFileType properties:nil ToTarget:hIconPath];
    [[AppsImageEngine sharedEngine] saveImage:xhIconImage saveType:NSPNGFileType properties:nil ToTarget:xhIconPath];
    
    return YES;
}


@end
